package com.ifast.asset.util;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

public class JsonUtil {

    //将json数组  解析出service名称
    public static List<String> parseService(String jsonString) {

        List<String> lists = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(jsonString);
            for (int i = 0; i < array.length(); i++) {

                JSONObject string = JSONObject.parseObject(array.get(i).toString());
                String serviceName = string.getString("service") + "(" + string.getString("port") + ")";
                lists.add(serviceName);
            }

        } catch (Exception e) {

            e.printStackTrace();
        }
        return lists;
    }

    //将json数组  解析出端口号
    public static List<Integer> parseService2(String jsonString) {

        List<Integer> lists = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(jsonString);
            for (int i = 0; i < array.length(); i++) {
                try {
                    JSONObject string = JSONObject.parseObject(array.get(i).toString());
                    int portnum = Integer.valueOf(string.getString("port"));
                    lists.add(portnum);
                } catch (Exception e) {

                }
            }

        } catch (Exception e) {

            e.printStackTrace();
        }
        return lists;
    }

    public static void main(String[] args) {

        String jsonString = "[{\"reason\":\"syn-ack\",\"product\":\"OpenSSH\",\"port\":\"22\",\"service\":\"ssh\",\"state\":\"open\",\"type\":\"tcp\",\"version\":\"7.4\",\"extrainfo\":\"protocol 2.0\"},{\"reason\":\"syn-ack\",\"product\":\"nginx\",\"port\":\"80\",\"service\":\"http\",\"state\":\"open\",\"type\":\"tcp\",\"version\":\"1.7.4\",\"extrainfo\":\"\"},{\"reason\":\"syn-ack\",\"product\":\"\",\"port\":\"514\",\"service\":\"shell\",\"state\":\"open\",\"type\":\"tcp\",\"version\":\"\",\"extrainfo\":\"\"},{\"reason\":\"syn-ack\",\"product\":\"MySQL\",\"port\":\"3306\",\"service\":\"mysql\",\"state\":\"open\",\"type\":\"tcp\",\"version\":\"\",\"extrainfo\":\"Host blocked because of too many connections\"},{\"reason\":\"syn-ack\",\"product\":\"\",\"port\":\"8080\",\"service\":\"http-proxy\",\"state\":\"open\",\"type\":\"tcp\",\"version\":\"\",\"extrainfo\":\"\"},{\"reason\":\"syn-ack\",\"product\":\"\",\"port\":\"8086\",\"service\":\"d-s-n\",\"state\":\"open\",\"type\":\"tcp\",\"version\":\"\",\"extrainfo\":\"\"},{\"reason\":\"syn-ack\",\"product\":\"\",\"port\":\"8090\",\"service\":\"unknown\",\"state\":\"open\",\"type\":\"tcp\",\"version\":\"\",\"extrainfo\":\"\"}]";
        parseService(jsonString);
    }
}
